<template>
    <div class="mainPage">
        <div class="header">
            <div class="title-container unselectable">
                <div @click="backIndex()">管线数据排查系统</div>
            </div>
            <div class="backIndex" @click="backIndex()">返回首页</div>
            <div class="setImagePath" @click="setImagePath()">设置图片路径</div>
            <div class="importData" @click="importData()">导入数据</div>
            <div class="exportData" :class="{ 'isExport': isExportDataing }" @click="exportData()">导出数据</div>
            <input v-show="false" type="file" ref="fileInput" class="file-input" accept=".mdb,.jpg,.png,.bmp,.tif,.jpeg"
                @change="handleFileSelect"></input>
            <div class="header-menu">
                <div class="header-menu-item" @click="fullscreen">
                    <img width="22px" height="22px" src="@/assets/img/fullscreen.png" />
                </div>
                <div class="header-menu-item" @click="openConsolePage">
                    <el-tooltip content="后台管理" placement="top">
                        <img width="26px" height="26px" src="@/assets/img/management.png" />
                    </el-tooltip>
                </div>
                <div class="header-menu-item" @click="logout">
                    <el-tooltip content="退出登录" placement="top">
                        <img width="24px" height="24px" src="@/assets/img/logout.png" />
                    </el-tooltip>
                </div>
                <!--                <div class="header-menu-item">-->
                <!--                  <el-dropdown>-->
                <!--&lt;!&ndash;                    <svg data-v-be27f04b="" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"&ndash;&gt;-->
                <!--&lt;!&ndash;                         stroke-width="1.5" stroke="currentColor" class="w-6 h-6"&ndash;&gt;-->
                <!--&lt;!&ndash;                         style="width: 2.0rem; height: 2.0rem; margin-top: 12px; color: rgb(255, 255, 255); cursor: pointer;">&ndash;&gt;-->
                <!--&lt;!&ndash;                      <path data-v-be27f04b="" stroke-linecap="round" stroke-linejoin="round"&ndash;&gt;-->
                <!--&lt;!&ndash;                            d="M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75">&ndash;&gt;-->
                <!--&lt;!&ndash;                      </path>&ndash;&gt;-->
                <!--&lt;!&ndash;                    </svg>&ndash;&gt;-->
                <!--                    <img width="24px" height="24px" src="@/assets/img/fullscreen.png" />-->
                <!--                    <el-dropdown-menu slot="dropdown">-->
                <!--                      <el-dropdown-item @command="openConsolePage">&nbsp;后台管理&nbsp;</el-dropdown-item>-->
                <!--                      <el-dropdown-item @command="logout">&nbsp;退出登录&nbsp;</el-dropdown-item>-->
                <!--                    </el-dropdown-menu>-->
                <!--                  </el-dropdown>-->
                <!--                </div>-->
            </div>
        </div>
        <div class="body">
            <div class="left" v-show="leftMenuShow">
                <div class="left-title">
                    <span>
                        功能菜单
                    </span>
                </div>
                <div class="left-content">
                    <div class="left-content-menu"
                        :class="{ 'left-content-menu-confirmed': menuList[0].visible ? true : false }"
                        @click="menuList[0].visible = !menuList[0].visible">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" width="25px" viewBox="0 0 24 24"
                            stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
                            <path stroke-linecap="round" stroke-linejoin="round"
                                d="M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0-3.75-3.75M17.25 21 21 17.25"></path>
                        </svg>
                        <div>数据采集与分析</div>
                    </div>
                    <div class="left-content-submenu" v-show="menuList[0].visible">
                        <div @click="changeDataListVisible()">属性查看</div>
                    </div>
                    <!-- <div class="left-content-menu"
                        :class="{ 'left-content-menu-confirmed': menuList[1].visible ? true : false }"
                        @click="menuList[1].visible = !menuList[1].visible">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" width="25px" viewBox="0 0 24 24"
                            stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
                            <path stroke-linecap="round" stroke-linejoin="round"
                                d="M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0-3.75-3.75M17.25 21 21 17.25"></path>
                        </svg>
                        <div>数据管理</div>
                    </div> -->
                    <!-- <div class="left-content-submenu" v-show="menuList[1].visible">
                        <div>上传图层数据</div>
                        <div @click="updateImgPath()">更新图片路径</div>
                    </div> -->

                </div>
            </div>
            <div class="content" ref="content">
                <div class="map-container">
                    <div class="float-menu-item" @click="change">
                        <svg xmlns="http://www.w3.org/2000/svg" style="" fill="none" viewBox="0 0 24 24"
                            stroke-width="1.8" stroke="currentColor" class="w-6 h-6">
                            <path stroke-linecap="round" stroke-linejoin="round" v-if="leftMenuShow"
                                d="M18.75 19.5l-7.5-7.5 7.5-7.5m-6 15L5.25 12l7.5-7.5"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" v-else
                                d="M11.25 4.5l7.5 7.5-7.5 7.5m-6-15l7.5 7.5-7.5 7.5"></path>
                        </svg>
                    </div>
                    <!-- <SearchBar></SearchBar> -->
                    <MapToolbar @mapToolBarEvent="handleEvent"></MapToolbar>
                    <DragwindowLegend v-show="showLegendModal" @dragWindowEvent="handleEvent" title="图例" width="300px">
                    </DragwindowLegend>
                    <Map ref="mapboxMap" v-if="reloadMap" @updateZoom="handleUpdateZoom"
                        @updateLngLat="handleUpdateLngLat"></Map>
                </div>
                <div class="map-state-container" v-show="true">
                    <div>
                        缩放等级&nbsp;&nbsp;&nbsp;：&nbsp;{{ mapZoom.toFixed(2) }}
                    </div>
                    <div>
                        经纬度&nbsp;&nbsp;&nbsp;：&nbsp;{{ mapLnglat.lng + ',' + mapLnglat.lat }}
                    </div>
                    <div>底图&nbsp;&nbsp;&nbsp;：&nbsp;</div>
                    <div>
                        <el-radio-group v-model="baseMap" size="mini">
                            <el-radio-button label="天地图影像"></el-radio-button>
                            <el-radio-button label="天地图矢量"></el-radio-button>
                        </el-radio-group>
                    </div>
                    <div>
                        <!-- <el-switch v-model="pointLayerVisible" active-color="#13ce66" style="width: 40px;"
                            inactive-color="#ff4949">
                        </el-switch> -->
                        <el-checkbox v-model="pointLayerVisible">{{ pointLayerVisible ? '显示点图层' : '隐藏点图层'
                            }}</el-checkbox>
                    </div>
                </div>
                <div class="layer-data-list" v-show="showDataList">
                    <div class="select-panel">
                        <div class="title">选择图层&nbsp;&nbsp;：&nbsp;&nbsp;</div>
                        <div><el-select v-model="layer" placeholder="请选择" size="mini">
                                <el-option v-for="item in layers" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select></div>
                        <div style="padding-left: 20px;">
                            <el-button size="mini" type="primary" @click="searchFeatures(layer)">查询</el-button>
                        </div>
                        <div class="right-flex">
                            <el-button size="mini" @click="changeDataListVisible()">关闭</el-button>
                        </div>
                    </div>
                    <div class="data-panel">
                        <ag-grid-vue style="height:260px;width:100%" class="ag-theme-balham" :columnDefs="columnDefs"
                            :rowData="rowData" :gridOptions="gridOptions" @grid-ready="onGridReady"></ag-grid-vue>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog title="更新图片路径" :visible.sync="dialogToUpdate" top="15%" width="480px" :append-to-body="true"
            :close-on-click-modal="false">
            <el-form :model="itemForm">
                <el-form-item label="">
                    <el-input v-model="itemForm.imagePath" placeholder="请输入图片路径"></el-input>
                </el-form-item>
                <div class="dialog-footer" style="text-align:right;">
                    <el-button type="primary" @click="confirmUpdateImgPath">确认</el-button>
                    <el-button @click="dialogToUpdate = false">取消</el-button>
                </div>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
import Map from '@/components/Map';
import SearchBar from '@/components/Map/components/searchBar.vue';
import MapToolbar from '../../components/Map/components/maptoolbar.vue';
import DragwindowLegend from '../../components/Map/components/dragwindow-legend.vue';
import editPage from '@/components/Map/components/editPage.vue';
import { AgGridVue } from "ag-grid-vue"
import { mapMutations, mapGetters } from 'vuex';
import PiplineProjectController from '../../api/Controller/PiplineProjectController';
import * as turf from '@turf/turf';
import { getToken, setToken, getFileType } from '@/utils';
import { SystemController } from '@/api';
import { EventBus } from '../../utils/bus';
import { PmDictDataController } from '@/api';
import config from '@/core/config/'
import axios from 'axios';

export default {
    name: 'PipelineIndex',
    data() {
        return {
            isFullScreen: false,
            leftMenuShow: true,
            mapZoom: 0,
            mapLnglat: { lng: 0, lat: 0 },
            baseMap: "天地图影像",
            showLegendModal: false, // 控制弹窗显示
            menuList: [
                { id: 1, name: "数据采集与分析", visible: true },
                { id: 2, name: "数据管理", visible: true },
                { id: 3, name: "其他", visible: true }
            ],

            rowData: [],
            gridOptions: {
                rowSelection: "multiple", //设置多好可选
                rowMultiSelectWithClick: false, //点击及选择复选框
                // suppressCellSelection: true, //点击不选中单元格
                enableCellTextSelection: true,
                defaultColDef: {
                    editable: false,
                    filter: true  //可过滤筛选
                },

                // onCellValueChanged: function (params) {
                //     // 处理单元格值更改的逻辑
                //     console.log("CellValueChanged:", params);

                //     // 获取发生更改的单元格元素
                //     var eCell = params.node.getCell(params.column.getColId());

                //     // 将修改后的值发送给后台，做验证
                //     // todo

                //     // 验证成功后，修改表单的值
                //     // todo

                //     // 添加高亮样式
                //     eCell.style.backgroundColor = "yellow"; // 或者其他你想要的颜色

                //     // 可以在一段时间后移除高亮，以避免一直高亮
                //     setTimeout(function () {
                //         eCell.style.backgroundColor = "";
                //     }, 1000); // 1秒后移除高亮
                // },
                onRowClicked: (event) => {
                    this.rowClicked(event);
                }
            },
            columnDefs: [
            ],

            layers: [],
            layer: '',

            // 展示数据列表
            showDataList: false,

            itemForm: {
                imagePath: ""
            },

            dialogToUpdate: false,

            isExportDataing: false,
            reloadMap: true, // 用于强制重新加载地图组件

            pointLayerVisible: true, // 控制点图层显示
        };
    },
    components: {
        Map, SearchBar, MapToolbar, DragwindowLegend, AgGridVue, editPage
    },
    mounted() {
        this.initVectorLayersOptions();
        // this.initPmDict()
    },
    created() {
        // EventBus.$off('showEditPage')
        EventBus.$on('showEditPage', (data) => {
            this.openEditPage(data)
        })
    },
    beforeDestroy() {
        EventBus.$off('showEditPage')
        this.$dialog.closeAll();
    },
    watch: {
        baseMap(newVal) {
            this.$refs.mapboxMap.changeBaseMap(newVal);
        },
        pointLayerVisible(newVal) {
            console.log('点图层显示状态改变：', newVal);
            // 得到当前项目的所有点图层key
            let config = this.getCurrentProjectConfig;
            console.log("config", config)
            if (config && config.data && config.data.length > 0) {
                let pointLayerKeys = [];
                for (let i = 0; i < config.data.length; i++) {
                    if (config.data[i].layerType === 'guandian') {
                        pointLayerKeys.push(config.data[i].layerId + "-point");
                    }
                }
                console.log("pointLayerKeys", pointLayerKeys)
                this.$refs.mapboxMap.setLayerVisibleByKeys(pointLayerKeys, newVal);
            } else {
                console.log("当前项目图层配置为空，无法设置点图层显示状态");
            }
        },
    },
    computed: {
        ...mapGetters(["getVectorLayerKeys", "getCurrentProjectConfig", "getPmDict"])
    },
    methods: {
        logout() {
            this.$confirm('是否退出登录？', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    let options = {
                        headers: {
                            Authorization: getToken()
                        },
                        showMask: false
                    };
                    SystemController.logout(this, {}, options).catch(e => { console.log("异常1", e) });
                    setToken();
                    window.sessionStorage.removeItem('isUaaLogin');
                    this.$router.replace({ name: 'login' });
                })
                .catch(e => {
                    console.log("异常2", e)
                });
        },
        openConsolePage() {
            console.log("进入控制台")// ✅ 正确做法：使用 window.open + router.resolve 获取 URL
            const routeData = this.$router.resolve({
                name: 'main', // 或 path: '/your-path'
            });
            window.open(routeData.href, '_blank');
        },
        openEditPage(data) {
            // this.showEditPage = true;
            console.log(data);
            console.log(this.getCurrentProjectConfig)
            if (!this.getCurrentProjectConfig.data || this.getCurrentProjectConfig.data.length === 0) {
                this.$message.error("获取图层配置出错，请刷新后重试");
            }
            let layerConfig = undefined
            let supportImage = false;
            let layerFields = [];
            for (let i = 0; i < this.getCurrentProjectConfig.data.length; i++) {
                if (this.getCurrentProjectConfig.data[i].layerId === data.layerId) {
                    // 将layerList字段保存下来
                    layerConfig = this.getCurrentProjectConfig.data[i];
                    layerFields = this.getCurrentProjectConfig.data[i].layerFields.filter(item => item.isEditField === 1);
                    supportImage = (this.getCurrentProjectConfig.data[i].supportImage === 1);
                }
            }

            if (layerFields.length === 0) {
                this.$message.error("获取图层字段出错，请刷新后重试");
            }

            let param = {
                ...data, fieldList: layerFields, supportImage: supportImage, layerConfig: layerConfig
            }
            console.log(param)
            let areaX = 500
            let areaY = (layerFields.length + 1) * 48 + 100 // 编辑字段的数量+1（按钮），再加上其他的100px左右

            let offsetTop = 80
            let offsetRight = 50
            let offsetMinBottom = 180
            if (supportImage) {
                areaY += 78
            }
            if ((areaY + offsetTop + offsetMinBottom) > window.innerHeight) {
              areaY = window.innerHeight - offsetTop - offsetMinBottom  // 上下预留100px、50px
            }
            let offsetLeft = (window.innerWidth - areaX - offsetRight)
            this.$dialog.closeAll() // TODO: 关闭所有窗口不太对，但是暂时没有好办法获取打开的窗口
            this.$dialog.show('编辑 ' + data.dataId, editPage, {
                type: 1,
                area: [areaX + 'px', areaY + 'px'],
                offset: [offsetTop + 'px', offsetLeft + 'px'],
                shade: 0
            }, param).then(res => {
            }).catch(e => { });
        },
        changeDataListVisible() {
            let that = this;
            this.showDataList = !this.showDataList;
            this.$nextTick(() => {
                // that.change(false);
                this.$refs.mapboxMap.handleResize();
            });
        },
        async handleFileSelect(e) {
            let that = this;
            console.log("文件选择：", e.target.files[0].name)
            let fileExtName = getFileType(e.target.files[0].name);
            try {
                // 创建FormData对象
                const formData = new FormData();
                formData.append('uploadFile', e.target.files[0]);
                if (fileExtName === 1) {
                    formData.append('asImage', true);
                } else {
                    formData.append('asImage', false);
                }

                // 发送请求
                const response = await axios.post(config.baseUrl + 'admin/app/dc/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': getToken() // 替换为实际的token获取逻辑
                    }
                });
                console.log("response1111111111111", response)
                // 处理响应
                if (response.status === 200) {
                    console.log('上传文件成功', response)
                    // showStatus('文件上传成功！', 'success');
                    // 上传成功后，再调用ImportProjectData接口
                    let params = {
                        responseInfo: {
                            uploadFailed: response.data.data.uploadFailed,
                            downloadUri: response.data.data.downloadUri,
                            uploadPath: response.data.data.uploadPath,
                            filename: response.data.data.filename,
                        },
                        projectId: this.getCurrentProjectConfig.projectId
                    };
                    console.log("输出params", params);
                    PiplineProjectController.ImportProjectData(this, params, null, { showMask: true }).then((res) => {
                        if (res.success) {
                            this.$message.success("文件上传成功");
                            this.reloadRealMap();
                        }
                        else
                            throw new Error(`ImportProjectData 失败：: ${res.errorMessage}`);
                    }).catch((err) => {
                        throw new Error(`ImportProjectData 失败：: ${err}`);
                    });
                } else {
                    throw new Error(`上传失败，状态码: ${response}`);
                }

            } catch (error) {
                console.error('上传出错:', error);
                this.$message.error('上传出错:', error);
                // showStatus(`上传失败: ${error.message || '未知错误'}`, 'error');
            } finally {
                // uploading.value = false;
                that.$refs.fileInput.value = "";
            }
        },
        // 计算边界范围
        calculateWktBbox(wkt, buffer = 0.0001) {
            if (!wkt) return null;

            // 统一转换为大写并移除多余空格
            const normalizedWkt = wkt.trim().toUpperCase();

            // 处理POINT类型
            if (normalizedWkt.startsWith('POINT')) {
                const match = normalizedWkt.match(/POINT\s*\(([^)]+)\)/);
                if (!match) return null;

                const coords = match[1].trim().split(/\s+/);
                if (coords.length < 2) return null;

                const lng = parseFloat(coords[0]);
                const lat = parseFloat(coords[1]);

                // 为点创建一个小边界框
                return [
                    lng - buffer,
                    lat - buffer,
                    lng + buffer,
                    lat + buffer
                ];
            }

            // 处理LINESTRING类型
            if (normalizedWkt.startsWith('LINESTRING')) {
                const match = normalizedWkt.match(/LINESTRING\s*\(([^)]+)\)/);
                if (!match) return null;

                const points = match[1].split(',').map(point => {
                    const coords = point.trim().split(/\s+/);
                    return coords.length >= 2 ?
                        [parseFloat(coords[0]), parseFloat(coords[1])] :
                        null;
                }).filter(Boolean);

                if (points.length === 0) return null;

                // 计算边界框
                let minLng = Infinity, maxLng = -Infinity;
                let minLat = Infinity, maxLat = -Infinity;

                points.forEach(([lng, lat]) => {
                    minLng = Math.min(minLng, lng);
                    maxLng = Math.max(maxLng, lng);
                    minLat = Math.min(minLat, lat);
                    maxLat = Math.max(maxLat, lat);
                });

                return [minLng, minLat, maxLng, maxLat];
            }

            // 处理POLYGON类型
            if (normalizedWkt.startsWith('POLYGON')) {
                const match = normalizedWkt.match(/POLYGON\s*\(\(([^)]+)\)\)/);
                if (!match) return null;

                const points = match[1].split(',').map(point => {
                    const coords = point.trim().split(/\s+/);
                    return coords.length >= 2 ?
                        [parseFloat(coords[0]), parseFloat(coords[1])] :
                        null;
                }).filter(Boolean);

                if (points.length === 0) return null;

                // 计算边界框
                let minLng = Infinity, maxLng = -Infinity;
                let minLat = Infinity, maxLat = -Infinity;

                points.forEach(([lng, lat]) => {
                    minLng = Math.min(minLng, lng);
                    maxLng = Math.max(maxLng, lng);
                    minLat = Math.min(minLat, lat);
                    maxLat = Math.max(maxLat, lat);
                });

                return [minLng, minLat, maxLng, maxLat];
            }

            // 处理其他类型（可选扩展）
            return null;
        },
        //
        wktToGeoJSON(wkt) {
            try {
                const type = wkt.split('(')[0].trim().toUpperCase();
                let coords = [];

                if (type === 'POINT') {
                    const match = wkt.match(/POINT\s*\(([^)]+)\)/);
                    if (!match) throw new Error('Invalid POINT format');
                    const [x, y] = match[1].trim().split(/\s+/).map(parseFloat);
                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: [x, y]
                        }
                    };
                }

                if (type === 'LINESTRING') {
                    const match = wkt.match(/LINESTRING\s*\(([^)]+)\)/);
                    if (!match) throw new Error('Invalid LINESTRING format');
                    coords = match[1].trim().split(',').map(pair => {
                        const [x, y] = pair.trim().split(/\s+/).map(parseFloat);
                        return [x, y];
                    });
                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'LineString',
                            coordinates: coords
                        }
                    };
                }

                if (type === 'POLYGON') {
                    const match = wkt.match(/POLYGON\s*\(\(([^)]+)\)\)/);
                    if (!match) throw new Error('Invalid POLYGON format');
                    coords = match[1].trim().split(',').map(pair => {
                        const [x, y] = pair.trim().split(/\s+/).map(parseFloat);
                        return [x, y];
                    });
                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'Polygon',
                            coordinates: [coords]
                        }
                    };
                }

                if (type === 'MULTIPOINT') {
                    const match = wkt.match(/MULTIPOINT\s*\(([^)]+)\)/);
                    if (!match) throw new Error('Invalid MULTIPOINT format');
                    const points = match[1].split(',').map(point => {
                        const cleanPoint = point.replace(/[()]/g, '').trim();
                        const [x, y] = cleanPoint.split(/\s+/).map(parseFloat);
                        return [x, y];
                    });
                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'MultiPoint',
                            coordinates: points
                        }
                    };
                }

                if (type === 'MULTIPOLYGON') {
                    const polygons = [];
                    const match = wkt.match(/MULTIPOLYGON\s*\((.+)\)/);
                    if (!match) throw new Error('Invalid MULTIPOLYGON format');

                    const polyStrings = match[1].split(')),((').map(s => s.replace(/[()]/g, ''));

                    polyStrings.forEach(polyStr => {
                        const rings = polyStr.split('),(');
                        const polygon = [];

                        rings.forEach(ring => {
                            const ringCoords = ring.split(',').map(pair => {
                                const [x, y] = pair.trim().split(/\s+/).map(parseFloat);
                                return [x, y];
                            });
                            polygon.push(ringCoords);
                        });

                        polygons.push(polygon);
                    });

                    return {
                        type: 'Feature',
                        geometry: {
                            type: 'MultiPolygon',
                            coordinates: polygons
                        }
                    };
                }

                throw new Error('Unsupported geometry type: ' + type);
            } catch (error) {
                throw new Error('WKT解析错误: ' + error.message);
            }
        },
        rowClicked(event) {
            //event.data 选中的行内数据，event.event 为鼠标事件，等其他。可以log自己看一下
            console.log('a row was clicked', event);
            // console.log("xxxxx", event.data.geometry.match(/LINESTRING \(([^)]+)\)/));
            // const coords = event.data.geometry.match(/LINESTRING \(([^)]+)\)/)[1];
            // const points = coords.split(', ').map(coord => {
            //     return coord.split(' ').map(Number);
            // });

            // const line = turf.lineString(points);

            // // 计算边界框
            // const bbox = turf.bbox(line);

            // // 转换为Mapbox格式 [[minLng, minLat], [maxLng, maxLat]]
            // const mapboxBbox = [
            //     [bbox[0], bbox[1]],
            //     [bbox[2], bbox[3]]
            // ];
            const mapboxBbox = this.calculateWktBbox(event.data.geometry);
            // let geoJSON = this.wktToGeoJSON(event.data.geometry);
            // // console.log("边界框：", mapboxBbox)
            // const centroid = turf.centroid(geoJSON);
            // console.log("centroid", centroid)
            // this.$refs.mapboxMap.addLocateIcon(centroid.geometry.coordinates[0], centroid.geometry.coordinates[1]);
            this.$map.fitBounds(mapboxBbox, {
                padding: 50,
                duration: 1000,
                maxZoom: 20,
            });
        },
        initVectorLayersOptions() {
            let that = this;
            this.layers = [];
            setTimeout(() => {
                let layers = that.getVectorLayerKeys;
                // for (let i = 0; i < layers.length; i++) {
                //     that.layers.push({ value: layers[i], label: layers[i] });
                // }
                Object.keys(layers).forEach((key) => {
                    that.layers.push({ value: key, label: layers[key] });
                });
            }, 1000);
        },
        zoomToLineStringTurf(wkt, padding = 50) {
            // 解析WKT为Turf LineString
            const coords = wkt.match(/LINESTRING \(([^)]+)\)/)[1];
            const points = coords.split(', ').map(coord => {
                return coord.split(' ').map(Number);
            });

            const line = turf.lineString(points);

            // 计算边界框
            const bbox = turf.bbox(line);

            // 转换为Mapbox格式 [[minLng, minLat], [maxLng, maxLat]]
            const mapboxBbox = [
                [bbox[0], bbox[1]],
                [bbox[2], bbox[3]]
            ];

            this.$refs.mapboxMap.map.fitBounds(mapboxBbox, {
                padding: padding,
                duration: 1000
            });
        },
        importData() {
            this.$refs.fileInput.click();
        },
        exportData() {
            this.isExport = !this.isExport;
            this.isExportDataing = this.isExport;
            if (this.isExport) {
                this.$message.info("请绘制导出范围")
                this.$refs.mapboxMap.draw.changeMode('draw_polygon');
                // 关闭地图响应事件
                this.setVectorLayerActive(false);
            } else {
                this.$refs.mapboxMap.draw.trash();
                // 开启地图响应事件
                this.setVectorLayerActive(true);
            }
        },
        /**
            * @description: 表格准备就绪 挂载属性及api
            * @param {Object} params - 表格实例
            * @return {*}
            */
        onGridReady(params) {
            // this.gridApi = params.api;
            // this.columnApi = params.columnApi;
            // // 这时就可以通过gridApi调用ag-grid的传统方法了
            // this.gridApi.sizeColumnsToFit();
            this.gridOptions.onRowClick = (event) => {
                console.log(event)
            }
        },
        backIndex() {
            let that = this;
            this.$confirm('确定要返回首页？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                that.$router.replace({ name: 'pipelineManage' });
                that.setCurrentProjectConfig({});
                that.setVectorLayerKeys([]);
            })
                .catch(action => {

                });
        },
        // 处理各个组件传递的消息
        handleEvent(e) {
            // 组件名称
            // 事件名称
            // 内容
            if (e.component === 'mapToolBar' && e.event === 'legend') {
                // 显示/隐藏图例
                this.showLegendModal = e.visible;
                console.log("传来的消息", e)
            }
            else if (e.component === 'dragWindowLegend' && e.event === 'visible') {
                // 隐藏图例弹窗
                this.showLegendModal = e.visible;
            }
            console.log("传来的消息", e)
        },
        handleUpdateZoom(zoom) {
            this.mapZoom = zoom;
        },
        handleUpdateLngLat(lnglat) {
            this.mapLnglat = lnglat;
        },
        fullscreen() {
            if (this.isFullScreen) {
                document.exitFullscreen();
            } else {
                document.documentElement.requestFullscreen();
            }
            this.isFullScreen = !this.isFullScreen
        },
        change(nochangeLeftMenu = true) {
            let that = this;
            if (nochangeLeftMenu)
                this.leftMenuShow = !this.leftMenuShow
            this.$nextTick(() => {
                this.$refs.mapboxMap.handleResize();
            })
        },
        getColomnInfoByLayerId(layerId) {
            if (!layerId) return [];
            if (this.getCurrentProjectConfig.data !== undefined && this.getCurrentProjectConfig.data !== null && this.getCurrentProjectConfig.data.length !== 0) {
                for (let i = 0; i < this.getCurrentProjectConfig.data.length; i++) {
                    if (this.getCurrentProjectConfig.data[i].layerId === layerId) {

                        // 将layerList字段保存下来
                        let layerFields = this.getCurrentProjectConfig.data[i].layerFields;

                        let columns = [];
                        // 用listFields
                        if (this.getCurrentProjectConfig.data[i].listFields === undefined || this.getCurrentProjectConfig.data[i].listFields === null) {
                            this.$message.error("该图层没有配置列表字段");
                            return [];
                        }
                        for (let j = 0; j < this.getCurrentProjectConfig.data[i].listFields.length; j++) {

                            for (let k = 0; k < layerFields.length; k++) {
                                if (layerFields[k].name === this.getCurrentProjectConfig.data[i].listFields[j]) {
                                    columns[j] = {
                                        headerName: layerFields[k].displayName,//this.getCurrentProjectConfig.data[i].listFields[j].displayName,
                                        field: this.getCurrentProjectConfig.data[i].listFields[j],
                                        width: 200
                                    };
                                    break;
                                }
                            }
                        }
                        console.log("列表列名：", columns)
                        if (columns.length === 0) {
                            this.$message.warning("该图层没有配置列表字段");
                        }
                        return columns;
                    }
                }
            } else {
                return [];
            }
        },
        searchFeatures(layerId) {
            let that = this;
            // console.log("获取项目配置123123", layerId)
            console.log("获取项目配置123123", this.getCurrentProjectConfig)

            let { projectId, data } = this.getCurrentProjectConfig;
            let primaryKey = "";
            data.forEach(item => {
                if (item.layerId === layerId) {
                    primaryKey = item.primaryKey;
                }
            });

            // let keys = this.$refs.mapboxMap.getAllPropertyKeys(layer);
            // let columns = [];
            // keys.forEach((element, index) => {
            //     columns[index] = {
            //         headerName: element,
            //         field: element,
            //         width: 200
            //     }
            // });
            // 设置表格列定义，从项目配置获取
            let columns = this.getColomnInfoByLayerId(layerId);
            console.log("xxxxxxxxx", columns)
            // 在最右侧加编辑按钮，并冻结最右侧一列
            columns.push({
                headerName: "操作",
                field: "operation",
                width: 100,
                pinned: 'right',
                cellRenderer: (params) => {
                    let btn = document.createElement('button');
                    btn.innerHTML = '编辑';
                    btn.className = 'btn btn-sm btn-primary';
                    btn.style = "width: 40px; height:20px;line-height:10px; font-size:12px;";
                    btn.addEventListener('click', () => {
                        // 这里处理点击事件，params.data是当前行的数据
                        console.log('编辑按钮点击', params.data);
                        // 弹出内容
                        // 凑出projectId、layerId、dataId
                        let data = {
                            projectId: projectId,
                            layerId: layerId,
                            dataId: params.data[primaryKey]//得到当前图层的主键
                        }

                        EventBus.$emit("showEditPage", data);

                    });
                    return btn;
                }
            });
            this.columnDefs = columns;

            this.$nextTick(() => {
                let params = {
                    "layerId": layerId,
                    "queryFilter": {},
                    "projectId": projectId,
                    // "pageParam": {
                    //     "pageNum": 0,
                    //     "pageSize": 99999999,
                    //     "count": true
                    // }
                };
                // 从后台获取列表数据
                PiplineProjectController.ListLayerData(this, params, null, { showMask: false }).then((res) => {
                    console.log("GetProjectLayerGeoJson：", res)
                    // 点图层响应事件
                    that.rowData = res.data.dataList;
                }).catch((err) => {
                    console.error("获取GeoJson失败111：", err);
                });
                // console.log("xxxxxxxxx123213123")
                // that.rowData = that.$refs.mapboxMap.getAllPropertyValues("guanxian");
            })

        },
        setImagePath() {
            // 打开图片存储路径
            // 从项目配置得到图片路径
            this.dialogToUpdate = true;
            let imagePath = this.getCurrentProjectConfig.imagePath;
            console.log("当前项目图片路径", imagePath);
            if (imagePath !== undefined && imagePath !== null) {
                this.itemForm.imagePath = imagePath;
            }
        },
        reloadRealMap() {
            let that = this;
            this.reloadMap = false; // 触发地图重新加载
            setTimeout(() => {
                that.reloadMap = true; // 触发地图重新加载
            }, 400);
        },
        confirmUpdateImgPath() {
            console.log("确认图片路径...", this.itemForm.imagePath)
            if (this.itemForm.imagePath.length === 0) {
                this.$message.error("请输入图片路径");
            } else {
                // 调用接口更新图片路径
                let params = {
                    // ...this.getCurrentProjectConfig,
                    // imagePath: this.itemForm.imagePath
                    "projectDto": {
                        "projectId": this.getCurrentProjectConfig.projectId,
                        "imageDirectory": this.itemForm.imagePath,
                        "projectName": this.getCurrentProjectConfig.projectName
                    }
                };
                console.log("xxxxxxxxxxxxx", params)
                PiplineProjectController.UpdateProject(this, params, null, { showMask: true }).then((res) => {
                    this.$message.success("图片路径更新成功");
                    this.dialogToUpdate = false;
                    let temp = this.getCurrentProjectConfig;
                    temp.imagePath = this.itemForm.imagePath;
                    this.setCurrentProjectConfig(temp)
                    this.reloadRealMap();
                }).catch((err) => {
                    console.error("更新图片路径失败：", err);
                });
            }
        },
        // initPmDict() {
        //     PmDictDataController.listDictByTypeIds(this, {}).then(res => {
        //         this.setPmDict(res.data);
        //     })
        // },
        ...mapMutations(["setCurrentProjectConfig", 'setVectorLayerKeys', 'setVectorLayerActive', "setPmDict"]),
    }
};
</script>

<style lang="scss" scoped>
.mainPage {
    position: fixed;
    width: 100%;
    height: 100%;

    background-color: white !important;

    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    align-content: center;

    .header {
        width: 100%;
        height: 60px;
        // border: 1px solid red;
        background-color: #4F46E5 !important;

        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        align-content: center;

        .title-container {
            width: 400px;
            height: 100%;
            display: flex;
            cursor: pointer;
            justify-content: flex-start;
            align-items: center;
            align-content: center;
            // border: 1px solid sandybrown;

            font-family: "Arial Black", sans-serif;
            font-size: 2.0em;
            letter-spacing: -1px;
            color: white;

            div {
                margin-left: 60px;
            }
        }

        .backIndex,
        .exportData,
        .importData,
        .setImagePath {
            font-family: "Arial Black", sans-serif;
            font-size: 1.5em;
            letter-spacing: -1px;
            color: white;
            cursor: pointer;
        }

        .exportData,
        .importData,
        .setImagePath {
            margin-left: 50px;
        }

        .isExport {

            border: 1px solid #aaa;
            padding: 10px;
            border-radius: 5px;
            box-shadow: inset 0 0 2px 2px #aaa;
        }

        // .btn:active {
        //     top: 4px;
        // }

        .header-menu {
            flex: 1;
            height: 100%;
            // border: 1px solid sandybrown;

            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center;
            align-content: center;

            .header-menu-item {
                width: 100;
                cursor: pointer;

                img {
                    margin-top: 12px;
                }
            }

            .header-menu-item {
                margin-right: 20px;
            }
        }
    }

    .body {
        width: 100%;
        flex: 1;
        // border: 1px solid seagreen;

        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        align-content: center;

        .left {
            width: 250px;
            height: 100%;
            // border: 1px solid blue;

            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            align-content: center;

            .left-title {
                width: 100%;
                height: 80px;
                display: flex;
                justify-content: flex-start;
                align-items: center;

                padding-left: 20px;

                span {
                    font-size: 16px;
                    font-weight: 500;
                    color: #4338EA;
                    background-color: #e0e7ff;
                    padding: 5px;
                }
            }

            .left-content {
                width: 100%;
                flex: 1;

                overflow: auto;

                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                align-items: center;
                align-content: center;

                padding: 0px 20px;

                .left-content-menu {
                    width: 100%;
                    height: 40px;

                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    align-content: center;
                    font-size: 14px;
                    font-weight: bold;

                    cursor: pointer;

                    div {
                        padding-left: 10px;
                    }
                }

                .left-content-menu:hover,
                .left-content-menu-confirmed {
                    color: #4F46E5;
                }

                .left-content-submenu {
                    width: 100%;

                    div {
                        width: 100%;
                        height: 35px;
                        padding-left: 40px;

                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        align-content: center;

                        font-size: 14px;
                        font-weight: bold;

                        cursor: pointer;
                    }

                    div:hover {
                        color: #4F46E5;
                    }
                }
            }
        }

        .float-menu-item {
            cursor: pointer;
            position: absolute;
            width: 40px;
            height: 40px;
            margin-top: 20px;
            border-top-right-radius: 5px;
            border-bottom-right-radius: 5px;
            padding: 8px;
            background-color: rgba(79, 70, 229, 0.9);
            color: white;
            z-index: 999;
        }

        .content {
            flex: 1;
            height: 100%;
            // border: 1px solid green;
            position: relative;

            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            align-content: center;

            .map-container {
                width: 100%;
                flex: 1;
                border: 1px solid rgb(138, 137, 135, 0.3);
                padding: 5px;
            }

            .map-state-container {
                border-left: 1px solid rgb(138, 137, 135, 0.3);
                width: 100%;
                height: 40px;
                // background-color: blueviolet;

                display: flex;
                justify-content: flex-start;
                align-items: center;
                align-content: center;

                font-size: 14px;

                div {
                    margin-left: 40px;
                }

                div:nth-child(2) {
                    width: 350px;
                    margin-left: 120px;
                }

                div:nth-child(3) {
                    margin-left: 120px;
                }

                div:nth-child(4) {
                    margin-left: -40px !important;
                }
            }

            .layer-data-list {
                width: 100%;
                height: 300px;
                border: 1px solid rgb(138, 137, 135, 0.3);

                .select-panel {
                    height: 40px;
                    width: 100%;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;

                    font-size: 14px;

                    .title {
                        padding-left: 40px;
                    }

                    .right-flex {
                        height: 100%;
                        flex: 1;

                        display: flex;
                        justify-content: flex-end;
                        align-items: center;

                        padding-right: 40px;
                    }

                    .data-panel {
                        width: 100%;
                        height: 260px;
                    }
                }
            }


        }
    }

    .unselectable {
        -webkit-user-select: none;
        /* Safari */
        -moz-user-select: none;
        /* Firefox */
        -ms-user-select: none;
        /* Internet Explorer/Edge */
        user-select: none;
        /* 标准语法 */
    }

    ::v-deep .layui-layer-content {
        padding: 10px !important;
    }
}
</style>
